<template>
  <a-modal
    v-model:open="openForm"
    width="60vw"
    :title="props.formType === 'add' ? '易宝资料录入' : '易宝资料修改'"
    :okText="'下一步'"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="p-y-20px">
      <a-steps :current="current" size="small" :items="stepsItems" />
    </div>
    <a-form ref="formRef" :model="data" v-bind="formOptions" :rules="props.formType == 'view' ? {} : rules" :disabled="props.formType == 'view'">
      <a-row :gutter="16" v-if="current === 0">
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>超管及其证件信息:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="超管类型:" name="contactType">
            <SmartEnumSelect width="100%" v-model:value="data.contactType" enumName="CONTACT_TYPE_ENUM" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="联系人手机号:" name="mobilePhone">
            <a-input v-model:value="data.mobilePhone" placeholder="请输入联系人手机号" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="联系人邮箱:" name="contactEmail">
            <a-input v-model:value="data.contactEmail" placeholder="请输入联系人邮箱" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="证件正面照片:" name="idCardCopy">
            <a-upload
              v-model:file-list="data.idCardCopy"
              name="idCardCopy"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'idCardCopy')"
              :accept="limitUpload['idCardCopy'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'idCardCopy')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="证件国徽面照片:" name="idCardNational">
            <a-upload
              v-model:file-list="data.idCardNational"
              name="idCardNational"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'idCardNational')"
              :accept="limitUpload['idCardNational'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'idCardNational')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="证件姓名:" name="idCardName">
            <a-input v-model:value="data.idCardName" placeholder="请输入证件姓名" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="证件号码:" name="idCardNumber">
            <a-input v-model:value="data.idCardNumber" placeholder="请输入证件号码" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="证件居住地址:" name="idCardAddress">
            <a-input v-model:value="data.idCardAddress" placeholder="请输入证件居住地址" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="证件有效期起始时间:" name="cardPeriodBegin">
            <a-date-picker
              class="w-full"
              v-model:value="data.cardPeriodBegin"
              :valueFormat="'YYYY-MM-DD'"
              :disabled-date="(dataVal) => dataVal && data.cardPeriodEnd && dataVal + 8.64e7 - 1000 >= new Date(data.cardPeriodEnd).getTime()"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="证件是否长期有效:" name="docLongTerm">
            <div>
              <a-switch v-model:checked="data.docLongTerm" checked-children="是" un-checked-children="否" />
              <span style="margin-left: 30px; color: red" v-if="data.docLongTerm">证件长期有效无需填写证件有效截至日期。</span>
            </div>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="证件有效期截止时间:" name="cardPeriodEnd">
            <a-date-picker
              class="w-full"
              v-model:value="data.cardPeriodEnd"
              :valueFormat="'YYYY-MM-DD'"
              :disabled-date="(dataVal) => dataVal && data.cardPeriodBegin && dataVal <= new Date(data.cardPeriodBegin).getTime()"
              :disabled="data.docLongTerm || props.formType == 'view'"
            />
          </a-form-item>
        </a-col>
        <!--        <div style="width: 100%; margin-bottom: 10px; font-size: medium">-->
        <!--          <span>微信OpenID:</span>-->
        <!--        </div>-->
        <!--        <a-col class="gutter-row" :span="12">-->
        <!--          <a-form-item label="联系人OpenID:" name="openId">-->
        <!--            <a-input v-model:value="data.openId" placeholder="请输入联系人OpenID" />-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
        <!--        <a-col class="gutter-row" :span="12">-->
        <!--          <a-form-item label="业务办理授权函:" name="businessAuthorizationLetter">-->
        <!--            <div style="margin-bottom: 10px; color: red">-->
        <!--              <span>当超级管理员类型是经办人时，请上传业务办理授权函。 </span>-->
        <!--            </div>-->
        <!--            <a-upload-->
        <!--              v-model:file-list="data.businessAuthorizationLetter"-->
        <!--              name="businessAuthorizationLetter"-->
        <!--              :custom-request="(file) => uploadFunc(file, 'businessAuthorizationLetter')"-->
        <!--              :accept="limitUpload['businessAuthorizationLetter'].fileType.toString()"-->
        <!--              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'businessAuthorizationLetter')"-->
        <!--              :headers="{-->
        <!--                authorization: 'authorization-text',-->
        <!--              }"-->
        <!--            >-->
        <!--              <a-button>-->
        <!--                <upload-outlined />-->
        <!--                点击上传-->
        <!--              </a-button>-->
        <!--            </a-upload>-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
      </a-row>
      <a-row :gutter="16" v-if="current === 1">
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>行业信息:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业主体类型:" name="subjectType">
            <SmartEnumSelect width="100%" v-model:value="data.subjectType" enumName="SUBJECT_TYPE_ENUM" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="一级行业分类:" name="pIndustryCategory">
            <CustomSelect
              v-model:value="data.pIndustryCategory"
              :placeholder="'请选择一级行业分类'"
              :api="businessCategoryApi"
              :searchFlag="true"
              :queryParams="headParams"
              @change="(value) => changeIndustry(value)"
              value-field="categoryCode"
              label-field="categoryName"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="二级行业分类:" name="sIndustryCategory">
            <CustomSelect
              ref="qualificationRef"
              v-model:value="data.sIndustryCategory"
              :placeholder="'请先选择一级行业分类'"
              :api="businessCategoryApi"
              :searchFlag="true"
              :queryParams="qualificationParams"
              value-field="categoryCode"
              label-field="categoryName"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="特殊类型资质图片:" name="qualifications">
            <div style="margin-bottom: 10px; color: red">
              <span>{{ data.sIndustryCategory ? specialText(data?.sIndustryCategory) : null }}</span>
            </div>
            <a-upload
              v-model:file-list="data.qualifications"
              name="qualifications"
              :max-count="5"
              :custom-request="(file) => uploadFunc(file, 'qualifications')"
              :multiple="true"
              :accept="limitUpload['qualifications'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'qualifications')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>营业执照信息:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照照片:" name="licenseCopy">
            <a-upload
              v-model:file-list="data.licenseCopy"
              name="licenseCopy"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'licenseCopy')"
              :accept="limitUpload['licenseCopy'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'licenseCopy')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照号码:" :name="licenseCopyIsEmpty ? '' : 'licenseNumber'">
            <a-input v-model:value="data.licenseNumber" placeholder="请输入营业执照号码" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照法定代表人姓名:" :name="licenseCopyIsEmpty ? '' : 'legalPerson'">
            <a-input v-model:value="data.legalPerson" placeholder="请输入营业执照法定代表人姓名" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照地址:" :name="licenseCopyIsEmpty ? '' : 'licenseAddress'">
            <a-input v-model:value="data.licenseAddress" placeholder="请输入营业执照地址" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照商户名称:" :name="licenseCopyIsEmpty ? '' : 'merchantName'">
            <a-input v-model:value="data.merchantName" placeholder="请输入营业执照商户名称" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照有效期起始时间:" :name="licenseCopyIsEmpty ? '' : 'periodBegin'">
            <a-date-picker
              class="w-full"
              v-model:value="data.periodBegin"
              :valueFormat="'YYYY-MM-DD'"
              :disabled-date="(dataVal) => dataVal && data.periodEnd && dataVal + 8.64e7 - 1000 >= new Date(data.periodEnd).getTime()"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照是否长期有效:" :name="licenseCopyIsEmpty ? '' : 'longTerm'">
            <div>
              <a-switch v-model:checked="data.longTerm" checked-children="是" un-checked-children="否" />
              <span style="margin-left: 30px; color: red" v-if="data.longTerm">证件长期有效无需填写证件有效截至日期。</span>
            </div>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="营业执照有效期截止时间:" :name="licenseCopyIsEmpty ? '' : 'periodEnd'">
            <a-date-picker
              class="w-full"
              v-model:value="data.periodEnd"
              :valueFormat="'YYYY-MM-DD'"
              :disabled-date="(dataVal) => dataVal && data.periodBegin && dataVal <= new Date(data.periodBegin).getTime()"
              :disabled="data.longTerm || props.formType == 'view'"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="手持营业执照在经营场所的照片:" :name="licenseCopyIsEmpty ? '' : 'handLicenceCopy'">
            <a-upload
              v-model:file-list="data.handLicenceCopy"
              name="handLicenceCopy"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'handLicenceCopy')"
              :accept="limitUpload['handLicenceCopy'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'handLicenceCopy')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="开户许可证照片/银行卡照片:" name="openAccountLicenceCopy">
            <a-upload
              v-model:file-list="data.openAccountLicenceCopy"
              name="openAccountLicenceCopy"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'openAccountLicenceCopy')"
              :accept="limitUpload['openAccountLicenceCopy'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'openAccountLicenceCopy')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>

        <!--        <a-col class="gutter-row" :span="12">-->
        <!--          <a-form-item label="特殊行业信用卡活动费率:" name="creditActivitiesRate">-->
        <!--            <a-input v-model:value="data.creditActivitiesRate" placeholder="请输入信用卡活动费率" />-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>销售场景及服务电话:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="销售场景类型:" name="salesScenesType">
            <SmartEnumCheckbox width="100%" v-model:value="data.salesScenesType" enumName="SALES_SCENES_TYPE_ENUM_YEEPAY" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="服务电话:" name="servicePhone">
            <a-input v-model:value="data.servicePhone" placeholder="请输入服务电话" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12" v-if="data.mpFlag">
          <div>
            <a-collapse accordion>
              <a-collapse-panel header="公众号场景" forceRender>
                <div style="margin-bottom: 15px; color: red">
                  <span>代理商服务号或公众号AppID与商家服务号或公众号AppID，二选一必填。</span>
                </div>
                <a-form-item label="代理商服务号或公众号AppID:" :name="['mpInfo', 'mpAppid']">
                  <a-input v-model:value="data.mpInfo.mpAppid" placeholder="请输入" />
                </a-form-item>
                <a-form-item label="商家服务号或公众号AppID:" :name="['mpInfo', 'mpSubAppid']">
                  <a-input v-model:value="data.mpInfo.mpSubAppid" placeholder="请输入" />
                </a-form-item>
                <a-form-item label="服务号或公众号页面截图:" :name="['mpInfo', 'mpPics']">
                  <a-upload
                    v-model:file-list="data.mpInfo.mpPics"
                    name="mpPics"
                    :custom-request="(file) => uploadFunc(file, 'mpInfo.mpPics')"
                    :max-count="5"
                    :accept="limitUpload['mpPics'].fileType.toString()"
                    :before-upload="(file, fileList) => beforeUpload(file, fileList, 'mpPics')"
                    :headers="{
                      authorization: 'authorization-text',
                    }"
                  >
                    <a-button>
                      <upload-outlined />
                      点击上传
                    </a-button>
                  </a-upload>
                </a-form-item>
              </a-collapse-panel>
            </a-collapse>
          </div>
        </a-col>
        <a-col class="gutter-row" :span="12" v-if="data.miniProgramFlag">
          <div>
            <a-collapse accordion>
              <a-collapse-panel key="1" header="小程序场景" forceRender>
                <div style="margin-bottom: 15px; color: red">
                  <span>代理商小程序AppID与商家小程序AppID，二选一必填。</span>
                </div>
                <a-form-item label="代理商小程序AppID:" :name="['miniProgramInfo', 'miniProgramAppid']">
                  <a-input v-model:value="data.miniProgramInfo.miniProgramAppid" placeholder="请输入" />
                </a-form-item>
                <a-form-item label="商家小程序AppID:" :name="['miniProgramInfo', 'miniProgramSubAppid']">
                  <a-input v-model:value="data.miniProgramInfo.miniProgramSubAppid" placeholder="请输入" />
                </a-form-item>
                <a-form-item label="小程序截图:" :name="['miniProgramInfo', 'miniProgramPics']">
                  <a-upload
                    v-model:file-list="data.miniProgramInfo.miniProgramPics"
                    name="miniProgramPics"
                    :custom-request="(file) => uploadFunc(file, 'miniProgramInfo.miniProgramPics')"
                    :max-count="5"
                    :accept="limitUpload['miniProgramPics'].fileType.toString()"
                    :before-upload="(file, fileList) => beforeUpload(file, fileList, 'miniProgramPics')"
                    :headers="{
                      authorization: 'authorization-text',
                    }"
                  >
                    <a-button>
                      <upload-outlined />
                      点击上传
                    </a-button>
                  </a-upload>
                </a-form-item>
              </a-collapse-panel>
            </a-collapse>
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="16" v-if="current === 2">
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>结算账户信息:</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="银行账户类型:" name="bankAccountType">
            <SmartEnumSelect width="100%" v-model:value="data.bankAccountType" enumName="BANK_ACCOUNT_TYPE_ENUM" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="开户银行(针对直连银行):" name="accountBank">
            <CustomSelect
              style="width: 100%"
              ref="bankRef"
              v-model:value="data.accountBank"
              :placeholder="'请选择'"
              :api="bankApi.pageHead"
              @change="changeAccountBank"
              queryParamKey="nameLike"
              :initParams="{ code: data.accountBank }"
              :valueField="'code'"
              :labelField="'name'"
            />
            <!-- :queryParams="{ code01: data.accountBank }" -->
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="银行账号:" name="accountNumber">
            <a-input v-model:value="data.accountNumber" placeholder="请输入银行账号" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="银行支行:" name="bankBranchId">
            <CustomSelect
              ref="branchRef"
              style="width: 100%"
              v-model:value="data.bankBranchId"
              :placeholder="'请选择'"
              :api="bankApi.pageSub"
              @change="changeBranch"
              queryParamKey="nameLike"
              :initParams="{ interbankNo: data.bankBranchId }"
              :valueField="'interbankNo'"
              :labelField="'name'"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户行地区" name="bankAddressCode">
            <area-cascader style="width: 90%" v-model:value="data.bankAddressCode" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16" v-if="current === 3">
        <div style="width: 100%; margin-bottom: 10px; font-size: medium">
          <span>补充信息(仅在进件被驳回后要求填写):</span>
        </div>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="法人开户承诺函" name="legalPersonCommitment">
            <a-upload
              v-model:file-list="data.legalPersonCommitment"
              name="legalPersonCommitment"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'legalPersonCommitment')"
              :accept="limitUpload['legalPersonCommitment'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'legalPersonCommitment')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="法人开户意愿视频:" name="legalPersonVideo">
            <a-upload
              v-model:file-list="data.legalPersonVideo"
              name="legalPersonVideo"
              :max-count="1"
              :custom-request="(file) => uploadFunc(file, 'legalPersonVideo')"
              :accept="limitUpload['legalPersonVideo'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'legalPersonVideo')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="业务补充说明:" name="businessAdditionMsg">
            <a-input v-model:value="data.businessAdditionMsg" placeholder="请输入业务补充说明" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="业务补充照片:" name="businessAdditionPics">
            <a-upload
              v-model:file-list="data.businessAdditionPics"
              name="businessAdditionPics"
              :max-count="5"
              :custom-request="(file) => uploadFunc(file, 'businessAdditionPics')"
              :accept="limitUpload['businessAdditionPics'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'businessAdditionPics')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-button key="back" @click="handleCancel"> 取消 </a-button>
      <a-button type="primary" @click="previousStep" v-if="current !== 0"> 上一步 </a-button>
      <a-button type="primary" @click="nextStep" v-if="current !== 3"> 下一步 </a-button>
      <a-button key="submit" type="primary" @click="handleOk" v-if="props.formType != 'view' && current === 3"> 提交 </a-button>
    </template>
  </a-modal>
</template>

<script setup name="YeepayForm">
  import { computed, getCurrentInstance, nextTick, onMounted, reactive, ref, watch } from 'vue'
  import { message, Upload } from 'ant-design-vue'
  import { uploadFileOther } from '/@/api/support/file-api.js'
  import SmartEnumCheckbox from '/@/components/framework/smart-enum-checkbox/index.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import { SALES_SCENES_TYPE_ENUM } from '/@/constants/business/b-merchant/expand/expand-const.js'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { businessCategoryApi } from '/src/api/business/b-merchant/regist/business-category.js'
  import { bankApi } from '/@/api/business/b-operation/bank/bank-api.js'
  import _ from 'lodash'
  import AreaCascader from '/@/components/business/b-operation/area-cascader/index.vue'
  import { registUpdate, registAdd } from '/src/api/business/b-merchant/regist/regist-api.js'
  import { convertPathsToFiles, getSelectedOptions, getObjValue, setObjValue } from '/@/utils/common.js'
  import { myUpload } from '/@/utils/myUpload'
  import { isNum } from '/@/utils/validate'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {
        return {}
      },
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    formOptions: {
      type: Object,
      default: () => {
        return {
          layout: 'vertical',
          name: 'basic',
          autocomplete: 'off',
        }
      },
    },
    params: {
      type: Object,
      default: () => {
        return {}
      },
    },
  })

  const emit = defineEmits(['update:open', 'ok'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  // 步骤条
  const current = ref(0)
  const stepsItems = ref([
    {
      title: '',
    },
    {
      title: '',
    },
    {
      title: '',
    },
    {
      title: '',
    },
  ])
  // 下一步
  const nextStep = async () => {
    console.log('dataxiayibu==>', data.value)

    let res = await validateForm()
    if (!res) return
    current.value >= stepsItems.value.length - 1 ? (current.value = stepsItems.value.length - 1) : current.value++
  }
  // 上一步
  const previousStep = () => {
    current.value <= 0 ? (current.value = 0) : current.value--
  }
  const initData = {
    bankCode: undefined,
    bankAddressCode: undefined,
    contactName: undefined,
    merchantId: undefined,
    channelId: undefined,
    shopAddress: [],
    legalPersonVideo: [],
    legalPersonCommitment: [],
    docLongTerm: null,
    idCardCopy: null,
    idCardNational: null,
    businessAuthorizationLetter: null,
    licenseCopy: null,
    handLicenceCopy: null,
    openAccountLicenceCopy: null,
    qualifications: null,
    businessAdditionPics: null,
    contactType: null,
    mobilePhone: null,
    idCardName: null,
    idCardNumber: null,
    idCardAddress: null,
    cardPeriodBegin: null,
    cardPeriodEnd: null,
    contactEmail: null,
    // openId: null,
    subjectType: null,
    pIndustryCategory: null,
    qualificationType: null,
    sIndustryCategory: null,
    licenseNumber: null,
    legalPerson: null,
    licenseAddress: null,
    merchantName: null,
    periodBegin: null,
    periodEnd: null,
    longTerm: null,
    servicePhone: null,
    salesScenesType: [],
    creditActivitiesRate: null,
    bankAccountType: null,
    accountBank: null,
    accountNumber: null,
    bankBranchId: null,
    bankName: null,
    accountName: null,
    businessAdditionMsg: null,
    bizStoreFlag: false,
    bizStoreInfo: {
      bizStoreName: null,
      bizAddressCode: null,
      bizStoreAddress: null,
      indoorPic: [],
      storeEntrancePic: [],
      bizSubAppid: null,
    },
    bizStoreName: null,
    bizAddressCode: null,
    bizStoreAddress: null,
    indoorPic: [],
    storeEntrancePic: [],
    bizSubAppid: null,
    appInfo: {
      appAppid: null,
      appSubAppid: null,
      appPics: [],
    },
    appFlag: false,
    appAppid: null,
    appSubAppid: null,
    appPics: [],
    mpInfo: {
      mpAppid: null,
      mpSubAppid: null,
      mpPics: [],
    },
    mpFlag: false,
    // mpAppid: null,
    // mpSubAppid: null,
    // mpPics: [],
    miniProgramInfo: {
      miniProgramAppid: null,
      miniProgramSubAppid: null,
      miniProgramPics: [],
    },
    miniProgramFlag: false,
    // miniProgramAppid: null,
    // miniProgramSubAppid: null,
    // miniProgramPics: [],
    webInfo: {
      domain: null,
      webAuthorisation: null,
      webAppid: null,
    },
    webFlag: false,
    domain: null,
    weworkInfo: {
      subCorpId: null,
      weworkPics: [],
    },
    webAuthorisation: null,
    webAppid: null,
    weworkFlag: false,
    subCorpId: null,
    weworkPics: [],
  }

  // 表单校验
  const rules = ref({
    salesScenesType: [{ required: true, message: '销售场景类型不能为空!' }],
    contactType: [{ required: true, message: '超管类型不能为空' }],
    mobilePhone: [{ required: true, message: '联系人手机号不能为空' }],
    contactEmail: [{ required: true, message: '联系人邮箱不能为空' }],
    idCardCopy: [{ required: true, message: '证件正面照片不能为空' }],
    idCardNational: [{ required: true, message: '证件国徽面照片不能为空' }],
    idCardName: [{ required: true, message: '证件姓名不能为空' }],
    idCardNumber: [{ required: true, message: '证件号码不能为空' }],
    idCardAddress: [{ required: true, message: '证件居住地址不能为空' }],
    cardPeriodBegin: [{ required: true, message: '证件有效期起始时间不能为空' }],
    cardPeriodEnd: [
      {
        validator: (rule, value, callback) => {
          if (data.value.docLongTerm) {
            //提示不需要填
            return Promise.resolve()
          } else {
            if (value) {
              return Promise.resolve()
            } else {
              return Promise.reject(new Error('证件有效期截止时间不能为空'))
            }
          }
        },
        trigger: ['blur', 'change'],
      },
    ],
    // openId: [{ required: true, message: '联系人OpenID不能为空' }],
    subjectType: [{ required: true, message: '营业主体类型不能为空' }],
    pIndustryCategory: [{ required: true, message: '一级行业分类不能为空' }],
    sIndustryCategory: [{ required: true, message: '二级行业分类不能为空' }],
    licenseCopy: [
      {
        required: false,
        message: '营业执照照片不能为空',
      },
    ],
    licenseNumber: [{ required: true, message: '营业执照号码不能为空' }],
    legalPerson: [{ required: true, message: '营业执照法定代表人姓名不能为空' }],
    lecenseAddress: [{ required: true, message: '营业执照地址不能为空' }],
    merchantName: [{ required: true, message: '营业执照商户名称不能为空' }],
    periodBegin: [{ required: true, message: '营业执照有效期起始时间不能为空' }],
    periodEnd: [
      {
        validator: (rule, value, callback) => {
          if (data.value.longTerm) {
            //提示不需要填
            return Promise.resolve()
          } else {
            if (value) {
              return Promise.resolve()
            } else {
              return Promise.reject(new Error('证件有效期截止时间不能为空'))
            }
          }
        },
        trigger: ['blur', 'change'],
      },
    ],
    openAccountLicenceCopy: [{ required: true, message: '开户许可证照片/银行卡照片不能为空' }],
    creditActivitiesRate: [{ required: true, message: '特殊行业信用卡活动费率不能为空' }],
    servicePhone: [{ required: true, message: '服务电话不能为空' }],
    bizStoreInfo: {
      bizStoreName: [{ required: true, message: '线下场所名称不能为空' }],
      bizAddressCode: [{ required: true, message: '线下场所所在地区不能为空' }],
      bizStoreAddress: [{ required: true, message: '线下场所详细地址不能为空' }],
      storeEntrancePic: [{ required: true, message: '线下场所门头照片不能为空' }],
      indoorPic: [{ required: true, message: '线下场所内景照片不能为空' }],
    },
    appAppid: [
      {
        validator: customRequiredRule,
        requiredFields: ['appAppid', 'appSubAppid'], // 指定需要校验的字段
        message: '代理商应用AppID 或 商家应用AppID 至少有一个不能为空',
        trigger: ['blur', 'change'],
      },
    ],
    appSubAppid: [
      {
        validator: customRequiredRule,
        requiredFields: ['appAppid', 'appSubAppid'], // 指定需要校验的字段
        message: '代理商应用AppID 或 商家应用AppID 至少有一个不能为空',
        trigger: ['blur', 'change'],
      },
    ],
    appPics: [{ required: true, message: 'App截图不能为空' }],
    mpInfo: {
      mpAppid: [
        {
          validator: customRequiredRule,
          requiredFields: ['mpInfo.mpAppid', 'mpInfo.mpSubAppid'], // 指定需要校验的字段
          message: '代理商服务号或公众号AppID 或 商家服务号或公众号AppID 至少有一个不能为空',
          trigger: ['blur', 'change'],
        },
      ],
      mpSubAppid: [
        {
          validator: customRequiredRule,
          requiredFields: ['mpInfo.mpAppid', 'mpInfo.mpSubAppid'], // 指定需要校验的字段
          message: '代理商服务号或公众号AppID 或 商家服务号或公众号AppID 至少有一个不能为空',
          trigger: ['blur', 'change'],
        },
      ],
      mpPics: [{ required: false, message: '服务号或公众号页面截图不能为空' }],
    },
    miniProgramInfo: {
      miniProgramAppid: [
        {
          validator: customRequiredRule,
          requiredFields: ['miniProgramInfo.miniProgramAppid', 'miniProgramInfo.miniProgramSubAppid'], // 指定需要校验的字段
          message: '代理商小程序AppID 或 商家小程序AppID 至少有一个不能为空',
          trigger: ['blur', 'change'],
        },
      ],
      miniProgramSubAppid: [
        {
          validator: customRequiredRule,
          requiredFields: ['miniProgramInfo.miniProgramAppid', 'miniProgramInfo.miniProgramSubAppid'], // 指定需要校验的字段
          message: '代理商小程序AppID 或 商家小程序AppID 至少有一个不能为空',
          trigger: ['blur', 'change'],
        },
      ],
      miniProgramPics: [{ required: false, message: '小程序截图不能为空' }],
    },
    domain: [{ required: true, message: '互联网网站域名不能为空' }],
    subCorpId: [{ required: true, message: '商家企业微信CorpID不能为空' }],
    weworkPics: [{ required: true, message: '企业微信页面截图不能为空' }],
    bankAccountType: [{ required: true, message: '银行账户类型不能为空' }],
    accountBank: [{ required: true, message: '开户银行(针对直连银行)不能为空' }],
    accountNumber: [{ required: true, message: '银行账号不能为空' }, { validator: isNum }],
    bankBranchId: [{ required: true, message: '银行支行不能为空' }],
  })
  const formRef = ref()
  const data = ref(_.cloneDeep(initData))
  const licenseCopyIsEmpty = computed(() => {
    return _.isEmpty(data.value.licenseCopy)
  })
  const limitUpload = {
    qualifications: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    storeEntrancePic: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    indoorPic: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    appPics: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    mpPics: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    miniProgramPics: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    webAuthorisation: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    weworkPics: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    licenseCopy: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    handLicenceCopy: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    openAccountLicenceCopy: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    idCardCopy: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    idCardNational: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    contactIdDocCopy: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    contactIdDocCopyBack: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    businessAdditionPics: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    businessAuthorizationLetter: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    certCopy: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    legalPersonVideo: {
      fileType: ['.avi', '.wmv', '.mpeg', '.mp4', '.mov', '.mkv', '.flv', '.f4v', '.m4v', '.rmvb'],
      fileSize: 20,
    },
    legalPersonCommitment: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    certificateLetterCopy: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    idDocCopy: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    idDocCopyBack: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
    financeLicensePic: {
      fileType: ['.jpg', '.BMP', '.png'],
      fileSize: 2,
    },
  }
  const beforeUpload = (file, fileList, type) => {
    // 校检文件类型
    if (limitUpload[type].fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload[type].fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload[type].fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload[type].fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload[type].fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload[type].fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // console.log('file==>', file)
    // 确保获取到文件对象
    const fileObj = file.file
    if (!fileObj) {
      return
    }
    const response = await myUpload(file)
    console.log('response==>', response)
    let arr = getObjValue(data.value, fieldName).map((item) => {
      if (item.uid === fileObj.uid) {
        message.success(`${fileObj.name} 上传成功`)
        return response
      }
      return item
    })
    setObjValue(data.value, fieldName, arr)
  }

  function customRequiredRule(rule, value, callback) {
    // 获取所有需要校验的字段
    const requiredFields = rule.requiredFields || []
    // 获取表单数据
    const formData = data.value

    // 检查是否有至少一个字段有值
    const hasValue = requiredFields.some((field) => {
      return getObjValue(formData, field) || getObjValue(formData, field) === 0 // 确保 0 值也能通过校验
    })

    if (hasValue) {
      // 校验通过
      return Promise.resolve()
    } else {
      return Promise.reject(new Error(rule.message || '至少有一个字段必填'))
    }
  }

  // 表单校验
  const validateForm = async () => {
    let isValid = false
    try {
      await formRef.value.validate()
      isValid = true
    } catch (error) {
      // console.log('表单校验==》', error)
      message.warning(error.errorFields[0].errors)
      isValid = false
    }
    return isValid
  }

  const handleOk = () => {
    validateForm().then((isValid) => {
      if (isValid) {
        const param = { ..._.cloneDeep(data.value), ..._.cloneDeep(props.params) }
        param.idCardCopy = getUrlString(data.value.idCardCopy)
        param.idCardNational = getUrlString(data.value.idCardNational)
        param.licenseCopy = getUrlString(data.value.licenseCopy)
        param.handLicenceCopy = getUrlString(data.value.handLicenceCopy)
        param.openAccountLicenceCopy = getUrlString(data.value.openAccountLicenceCopy)
        param.qualifications = getUrlArray(data.value.qualifications)
        param.bizStoreInfo.storeEntrancePic = getUrlArray(data.value.bizStoreInfo.storeEntrancePic)
        param.bizStoreInfo.indoorPic = getUrlArray(data.value.bizStoreInfo.indoorPic)
        param.appInfo.appPics = getUrlArray(data.value.appInfo.appPics)
        param.mpInfo.mpPics = getUrlArray(data.value.mpInfo.mpPics)
        param.miniProgramInfo.miniProgramPics = getUrlArray(data.value.miniProgramInfo.miniProgramPics)
        param.webInfo.webAuthorisation = getUrlString(data.value.webInfo.webAuthorisation)
        param.weworkInfo.weworkPics = getUrlArray(data.value.weworkInfo.weworkPics)
        param.businessAdditionPics = getUrlArray(data.value.businessAdditionPics)
        param.legalPersonVideo = getUrlString(data.value.legalPersonVideo)
        param.legalPersonCommitment = getUrlString(data.value.legalPersonCommitment)
        // if (param.docLongTerm === true) {
        //   param.cardPeriodEnd = '长期'
        // }
        // if (param.longTerm === true) {
        //   param.periodEnd = '长期'
        // }

        if (props.formType === 'add') {
          registAdd(param).then(() => {
            message.success('提交成功')
            resetForm()
            openForm.value = false
            emit('ok', data.value)
          })
        } else if (props.formType === 'update') {
          registUpdate(param).then(() => {
            message.success('修改成功')
            resetForm()
            openForm.value = false
            emit('ok', data.value)
          })
        }
      }
    })
  }
  const getUrlString = (fileList) => {
    //判断数组长度，如果为1则返回第一个元素的url，如果为空则返回空字符串，如果大于1则返回所有元素的url的数组
    if (fileList && fileList.length === 1) {
      return fileList[0].url
    } else {
      return undefined
    }
  }
  const getUrlArray = (fileList) => {
    if (Array.isArray(fileList)) {
      let fileArr = [...fileList]
      return fileArr.map((file) => file.url)
    } else {
      return undefined
    }
  }

  const handleCancel = () => {
    openForm.value = false
    data.value = {}
    resetForm()
  }
  // const resetForm = () => {
  //   formRef.value.resetFields()
  // }

  const qualificationRef = ref(null)

  const specialText = (selectedValue) => {
    const option = getSelectedOptions(selectedValue, qualificationRef)
    return option ? option.qualificationsGuide : null
  }

  const branchRef = ref()
  const getBranchName = (selectedValue) => {
    const option = getSelectedOptions(selectedValue, branchRef)
    return option ? option.name : null
  }
  const bankRef = ref()
  const getBankCode = (selectedValue) => {
    const option = getSelectedOptions(selectedValue, bankRef)
    return option ? option.code : null
  }
  const headParams = computed(() => {
    return {
      pCategoryCode: '000000',
      channelType: props.params.channelType,
    }
  })
  const qualificationParams = computed(() => {
    return {
      pCategoryCode: data.value?.pIndustryCategory ? data.value?.pIndustryCategory : 'unknown',
      channelType: props.params.channelType,
    }
  })

  // 一级行业改变
  const changeIndustry = (val) => {
    data.value.sIndustryCategory = undefined
  }
  // 改变银行支行
  const changeBranch = (val, opt) => {
    data.value.bankName = opt.map((e) => e.name).toString()
  }
  // 改变开户银行(针对直连银行)
  const changeAccountBank = (val, opt) => {
    data.value.bankCode = opt.map((e) => e.code).toString()
  }

  // watch(
  //   () => data.value.bankBranchId,
  //   (newVal) => {
  //     if (newVal === undefined) {
  //       data.value.bankName = undefined
  //     } else {
  //       data.value.bankName = getBranchName(newVal)
  //     }
  //   },
  // )
  // watch(
  //   () => data.value.accountBank,
  //   (newVal) => {
  //     if (newVal === undefined) {
  //       data.value.bankCode = undefined
  //     } else {
  //       data.value.bankCode = getBankCode(newVal)
  //     }
  //   },
  // )

  watch(
    () => data.value.salesScenesType,
    (newVal) => {
      const salesScenes = Array.isArray(newVal) ? newVal : []
      // 根据 newVal 的值对其他属性赋值
      data.value.bizStoreFlag = salesScenes.includes(SALES_SCENES_TYPE_ENUM.BIZ_STORE.value)
      data.value.appFlag = salesScenes.includes(SALES_SCENES_TYPE_ENUM.APP.value)
      data.value.mpFlag = salesScenes.includes(SALES_SCENES_TYPE_ENUM.MP.value)
      data.value.miniProgramFlag = salesScenes.includes(SALES_SCENES_TYPE_ENUM.MINI_PROGRAM.value)
      data.value.webFlag = salesScenes.includes(SALES_SCENES_TYPE_ENUM.WEB.value)
      data.value.weworkFlag = salesScenes.includes(SALES_SCENES_TYPE_ENUM.WE_WORK.value)
    },
    { immediate: true },
  )

  watch(
    [() => props.formData, () => props.open],
    (newVal) => {
      if ((props.formType == 'update' || props.formType == 'view') && props.open) {
        show(_.cloneDeep(newVal[0]))
        console.log('data===>', data.value)
      }
    },
    { deep: true, immediate: true },
  )
  const resetForm = () => {
    // 重置表单数据
    data.value = _.cloneDeep(initData)
    // Object.assign(data.value, _.cloneDeep(initData))

    // 重置表单的 UI 状态
    formRef.value.resetFields()

    // 重置上传组件的文件列表
    const uploadFields = [
      'idCardCopy',
      'idCardNational',
      'licenseCopy',
      'handLicenceCopy',
      'openAccountLicenceCopy',
      'qualifications',
      'bizStoreInfo.storeEntrancePic',
      'bizStoreInfo.indoorPic',
      'appInfo.appPics',
      'mpInfo.mpPics',
      'miniProgramInfo.miniProgramPics',
      'webInfo.webAuthorisation',
      'weworkInfo.weworkPics',
      'businessAdditionPics',
      'legalPersonVideo',
      'legalPersonCommitment',
    ]

    uploadFields.forEach((field) => {
      // data.value[field] = null
      setObjValue(data.value, field, null)
    })

    // 重置步骤条
    current.value = 0
    console.log('重置表单')
  }
  // 在组件挂载时初始化地址选项
  onMounted(() => {
    // initAddressOptions()
  })

  function show(rowData) {
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(data.value, rowData)
    }
    console.log('rowData', rowData)

    data.value.idCardCopy = convertPathsToFiles(rowData.idCardCopy, '证件正面照片')
    data.value.idCardNational = convertPathsToFiles(rowData.idCardNational, '证件国徽面照片')
    data.value.qualifications = convertPathsToFiles(rowData.qualifications, '特殊类型资质图片')
    data.value.licenseCopy = convertPathsToFiles(rowData.licenseCopy, '营业执照照片')
    data.value.handLicenceCopy = convertPathsToFiles(rowData.handLicenceCopy, '手持营业执照在经营场所的照片')
    data.value.openAccountLicenceCopy = convertPathsToFiles(rowData.openAccountLicenceCopy, '开户许可证照片/银行卡照片')
    data.value.legalPersonCommitment = convertPathsToFiles(rowData.legalPersonCommitment, '法人开户承诺函')
    data.value.legalPersonVideo = convertPathsToFiles(rowData.legalPersonVideo, '法人开户意愿视频')
    data.value.businessAdditionPics = convertPathsToFiles(rowData.businessAdditionPics, '业务补充照片')
    data.value.mpInfo.mpPics = convertPathsToFiles(rowData?.mpInfo?.mpPics, '服务号或公众号页面截图')
    data.value.miniProgramInfo.miniProgramPics = convertPathsToFiles(rowData?.miniProgramInfo?.miniProgramPics, '小程序截图')
  }
  defineExpose({
    formRef,
    show,
  })
</script>

<style lang="scss" scoped></style>
